<template>
  <div>
    <!-- 查询条件 -->
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="角色名称">
        <el-input
          v-model="formInline.roleName"
          placeholder="请输入角色名称"
          clearable
        />
      </el-form-item>

      <el-form-item>
        <el-button type="danger" @click="search()">搜索</el-button>
        <el-button type="danger" @click="addRole()">新增角色</el-button>
      </el-form-item>
    </el-form>

    <!-- 信息显示列表 -->
    <el-table :data="tableData">
      <el-table-column label="序号" width="60">
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>

      <el-table-column
        prop="roleName"
        label="角色名称"
        align="center"
        width="200"
      />

      <el-table-column
        prop="roleDescribe"
        label="角色描述"
        align="center"
        width="200"
      />

      <el-table-column prop="createBy" label="创建人" align="center" />

      <el-table-column label="创建时间" width="200" align="center">
        <template #default="scope">
          <span v-if="scope.row.createDate != null">{{
            scope.row.createDate.replace("T", " ").substr(0, 19)
          }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="updateBy" label="修改人" align="center" />

      <el-table-column label="修改时间" width="200" align="center">
        <template #default="scope">
          <span v-if="scope.row.updateDate != null">{{
            scope.row.updateDate.replace("T", " ").substr(0, 19)
          }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center">
        <template v-slot="scope">
          <el-button
            link
            type="primary"
            v-show="scope.row.roleName != '超级管理员'"
            @click="updRole(scope.row.roleId)"
            >编辑</el-button
          >
          <el-button
            link
            type="primary"
            v-show="scope.row.roleName != '超级管理员'"
            @click="delRole(scope.row.roleId)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[15, 20, 35, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 角色添加弹框 -->
    <el-dialog
      v-model="dialogFormVisibleAdd"
      width="600"
      title="角色添加"
      text-align="center"
    >
      <el-form
        ref="ruleFormRef"
        style="width: 400px"
        :model="ruleFormAdd"
        :rules="rulesAdd"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="名称" prop="roleName">
          <el-input v-model="ruleFormAdd.roleName" />
        </el-form-item>

        <el-form-item label="描述" prop="roleDescribe">
          <el-input v-model="ruleFormAdd.roleDescribe" type="textarea" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="submitFormAdd(ruleFormRef)">
            保存
          </el-button>
          <el-button type="danger" @click="resetForm(ruleFormRef)"
            >重置</el-button
          >
        </div>
      </template>
    </el-dialog>

    <!-- 角色修改弹框 -->
    <el-dialog
      v-model="dialogFormVisibleUpd"
      width="600"
      title="角色添加"
      text-align="center"
    >
      <el-form
        ref="ruleFormRef"
        style="width: 400px"
        :model="ruleFormUpd"
        :rules="rulesUpd"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="名称" prop="roleName">
          <el-input v-model="ruleFormUpd.roleName" />
        </el-form-item>

        <el-form-item label="描述" prop="roleDescribe">
          <el-input v-model="ruleFormUpd.roleDescribe" type="textarea" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="submitFormUpd(ruleFormRef)">
            保存
          </el-button>
          <el-button type="danger" @click="resetForm(ruleFormRef)"
            >重置</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import axios from "axios";
import { reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import {
  type FormInstance,
  type FormRules,
  ElMessage,
  ElMessageBox,
} from "element-plus";
import http from "@/http";

const router = useRouter();

//角色添加弹框
const dialogFormVisibleAdd = ref(false);

interface RuleFormAdd {
  roleName: string;
  roleDescribe: string;
  createBy: string;
  isDel: boolean;
}

const ruleFormRef = ref<FormInstance>();
//角色添加表单
const ruleFormAdd = reactive<RuleFormAdd>({
  roleName: "",
  roleDescribe: "",
  createBy: "",
  isDel: false,
});

//验证
const rulesAdd = reactive<FormRules<RuleFormAdd>>({
  roleName: [{ required: true, message: "请输入名称", trigger: "blur" }],

  roleDescribe: [
    { required: true, message: "请输入角色描述", trigger: "blur" },
  ],
});

//角色修改弹框
const dialogFormVisibleUpd = ref(false);

interface RuleFormUpd {
  roleId: string;
  roleName: string;
  roleDescribe: string;
  createBy: string;
  createDate: string;
  UpdateBy: string;
  isDel: string;
}

//角色修改表单
const ruleFormUpd = reactive<RuleFormUpd>({
  roleId: "",
  roleName: "",
  roleDescribe: "",
  createBy: "",
  createDate: "",
  UpdateBy: "",
  isDel: "",
});

//验证
const rulesUpd = reactive<FormRules<RuleFormUpd>>({
  roleName: [{ required: true, message: "请输入名称", trigger: "blur" }],

  roleDescribe: [
    { required: true, message: "请输入角色描述", trigger: "blur" },
  ],
});

//查询条件
const formInline = reactive({
  roleName: "",
});

//角色信息
const tableData = ref();

//分页
const currentPage = ref(1);
const pageSize = ref(15);
const totalCount = ref(0);

//获取角色信息
const getRole = () => {
  http
    .get("Readroute/api/RoleInfo/GetRole", {
      params: {
        roleName: formInline.roleName || null,
        pageIndex: currentPage.value,
        pageSize: pageSize.value,
      },
    })
    .then((res) => {
      //console.log(res.data);
      tableData.value = res.data.datas;
      totalCount.value = res.data.totalCount;
    });
};

//页容量改变
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  //console.log(`${val} items per page`);
  getRole();
};
//页序号改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  //console.log(`current page: ${val}`);
  getRole();
};

//查询
const search = () => {
  currentPage.value = 1;
  getRole();
};

//角色添加弹出层
const addRole = () => {
  const staffId = localStorage.getItem("staffId");

  http
    .get("Readroute/api/StaffInfo/GetStaffInfo?staffId=" + staffId)
    .then((res) => {
      ruleFormAdd.createBy = res.data.staffName;
    });

  dialogFormVisibleAdd.value = true;
};

//角色添加
const submitFormAdd = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      http.post("route/api/Role/AddRole", ruleFormAdd).then((res) => {
        if (res.data == 0) {
          ElMessage.error("此角色已存在！");
        } else {
          ElMessage({
            message: "保存成功！",
            type: "success",
          });
          dialogFormVisibleAdd.value = false;
          getRole();
        }
      });
    } else {
      return;
    }
  });
};

//修改角色弹出层
const updRole = (roleId: number) => {
  const staffId = localStorage.getItem("staffId");

  http
    .get("Readroute/api/StaffInfo/GetStaffInfo?staffId=" + staffId)
    .then((res) => {
      ruleFormUpd.UpdateBy = res.data.staffName;
    });

  http
    .get("Readroute/api/RoleInfo/GetRoleInfo?roleId=" + roleId)
    .then((res) => {
      //console.log(res.data);
      ruleFormUpd.roleId = res.data.roleId;
      ruleFormUpd.roleName = res.data.roleName;
      ruleFormUpd.roleDescribe = res.data.roleDescribe;
      ruleFormUpd.createBy = res.data.createBy;
      ruleFormUpd.createDate = res.data.createDate;
      ruleFormUpd.isDel = res.data.isDel;
    });

  dialogFormVisibleUpd.value = true;
};

//角色修改
const submitFormUpd = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      http.put("route/api/Role/UpdRole", ruleFormUpd).then((res) => {
        if (res.data == 0) {
          ElMessage.error("此角色已存在！");
        } else {
          ElMessage({
            message: "保存成功！",
            type: "success",
          });
          dialogFormVisibleUpd.value = false;
          getRole();
        }
      });
    } else {
      return;
    }
  });
};

//重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

//角色删除
const delRole = (roleId: number) => {
  //console.log(roleId);

  ElMessageBox.confirm("确定要删除吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "error",
  })
    .then(() => {
      http.delete("route/api/Role/DelRole?roleId=" + roleId).then((res) => {
        if (res.data == 1) {
          ElMessage({
            message: "删除成功！",
            type: "success",
          });
          getRole();
        }
      });
    })
    .catch(() => {});
};

//加载
onMounted(() => {
  getRole();
});
</script>

<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>